<template>
    <a-dropdown placement="bottomRight" :get-popup-container="getPopupContainer">
        <div class="user-name">
            <slot name="prefixIcon"></slot>{{ userName }}
            <component :is="dropdownIcon" />
        </div>
        <template #overlay>
            <a-menu>
                <a-menu-item key="editPassWord" @click="handlePassWord">
                    {{ t('editPassWord') }}
                </a-menu-item>
                <a-menu-item key="logout" @click="handleLogout">
                    {{ t('logout') }}
                </a-menu-item>
            </a-menu>
        </template>
    </a-dropdown>
    <a-modal
        v-model:visible="showModal"
        :destroy-on-close="true"
        :title="t('editPassWord')"
        centered
        :mask-closable="false"
        @ok="handleSubmit"
    >
        <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 14, push: 1 }"
        >
            <a-form-item :label="t('oldPassword')" name="oldPassword">
                <a-input-password v-model:value="formState.oldPassword" type="password" />
            </a-form-item>
            <a-form-item :label="t('newPassWord')" name="newPassword">
                <a-input-password v-model:value="formState.newPassword" type="password" />
            </a-form-item>
            <a-form-item :label="t('reNewPassword')" name="rePassword">
                <a-input-password v-model:value="formState.rePassword" type="password" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts" setup>
    import { computed, reactive, ref } from 'vue'
    import { useUserStore } from '@/store/modules/user'
    import { useRouter } from 'vue-router'

    import { useI18n } from 'vue-i18n'
    import type { RuleObject } from 'ant-design-vue/es/form'
    import type { FormInstance } from 'ant-design-vue'
    import md5 from 'js-md5'
    import { updatePassword } from '@/apis/sys/user'
    import { message } from 'ant-design-vue'
    import { ROUTER_NAME } from '@/constant'

    function isPasswordRegExp(value) {
        const passwordPattern = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,20}$/
        return passwordPattern.test(value)
    }
    const { t } = useI18n()
    const props = defineProps({
        popupContainer: {
            type: String,
            default: 'parentNode' // body(document.body)parentNode (triggerNode.parentNode)
        },
        dropdownIcon: {
            type: String,
            default: 'caret-down-outlined' // 默认实心三角
        }
    })
    const userStore = useUserStore()
    const router = useRouter()

    const userName = computed(() => userStore.name)
    // 用于DPA导航用户属性下拉框样式设置
    const getPopupContainer = computed(() => {
        return triggerNode => {
            return props.popupContainer === 'parentNode' ? triggerNode.parentNode : document.body
        }
    })
    const showModal = ref<boolean>(false)

    const handleLogout = () => {
        userStore.logout()
        router.push({ name: ROUTER_NAME.PAGE_LOGIN })
    }

    const formState = reactive({
        oldPassword: '',
        newPassword: '',
        rePassword: ''
    })

    const validatePassword = (rule: RuleObject, value: string) => {
        if (!isPasswordRegExp(value)) {
            return Promise.reject(t('passwordRegExpMessage'))
        } else {
            return Promise.resolve()
        }
    }
    const validateRePassword = (rule: RuleObject, value: string) => {
        if (!isPasswordRegExp(value)) {
            return Promise.reject(t('passwordRegExpMessage'))
        } else if (value !== formState.newPassword) {
            return Promise.reject(t('inequalityMessage'))
        } else {
            return Promise.resolve()
        }
    }
    const rules = {
        oldPassword: [{ required: true, message: t('oldPasswordMessage'), trigger: 'blur' }],
        newPassword: [
            { required: true, message: t('newPasswordMessage'), trigger: 'blur' },
            {
                min: 6,
                max: 20,
                message: t('passwordMinMaxMessage', { min: 6, max: 20 }),
                trigger: 'blur'
            },
            { validator: validatePassword, trigger: 'blur' }
        ],
        rePassword: [
            { required: true, message: t('reNewPasswordMessage'), trigger: 'blur' },
            {
                min: 6,
                max: 20,
                message: t('passwordMinMaxMessage', { min: 6, max: 20 }),
                trigger: 'blur'
            },
            { validator: validateRePassword, trigger: 'blur' }
        ]
    }

    const handlePassWord = () => {
        showModal.value = true
    }

    const formRef = ref<FormInstance>()
    const handleSubmit = () => {
        formRef.value &&
            formRef.value.validateFields().then(() => {
                const params = {
                    mobile: userStore.getUserInfo.mobile,
                    oldPassword: md5(formState.oldPassword),
                    password: md5(formState.newPassword)
                }
                updatePassword(params)
                    .then(() => {
                        message.success(t('changePasswordSuccess'))
                    })
                    .then(() => {
                        showModal.value = false
                        userStore.logout()
                        router.push({ name: ROUTER_NAME.PAGE_LOGIN })
                    })
            })
    }
</script>

<style lang="less" scoped>
    .user-name {
        cursor: pointer;
    }

    :deep(.@{ant-prefix}-modal-title) {
        text-align: center;
    }
</style>
<i18n>
zh-CN:
    editPassWord: 修改密码
    logout: 登出
    oldPassword: 原密码
    newPassWord: 新密码,
    reNewPassword: 确认新密码,
    oldPasswordMessage: 请输入原密码
    newPasswordMessage: 请输入新密码
    reNewPasswordMessage: 请输入确认新密码
    passwordRegExpMessage: 字母（区分大小写）、数字、特殊字符两种及以上
    inequalityMessage: 两次输入密码不一致，请重新输入
    passwordMinMaxMessage: 密码长度{min}-{max}个字符
    changePasswordSuccess: 密码修改成功
en-US:
    editPassWord: Change Password
    logout: Log out
    oldPassword: old Password
    newPassWord: new password
    reNewPassword: Confirm new password
    oldPasswordMessage: Please enter the password
    newPasswordMessage: Please enter a new password
    reNewPasswordMessage: Please enter confirm new password
    passwordRegExpMessage: Two or more letters (case sensitive), numbers, and special characters
    inequalityMessage: The two passwords are inconsistent, please re-enter
    passwordMinMaxMessage: Password length {min}-{max} characters
    changePasswordSuccess: Password modified successfully
</i18n>
